package cn.huapu.power.energy.ex;

import cn.huapu.power.energy.vo.Ret;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局的的异常处理器，返回处理的信息
 * @author hunter
 * 
 */
@RestControllerAdvice
public class RestExceptionHandler {
	private Log log = LogFactory.getLog(RestExceptionHandler.class);
	/**
	 * 全局异常.
	 * @param e the Exception
	 * @return Ret
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Ret exception(Exception e) {
		Ret r= new Ret();
		log.error("全局异常信息 ", e);
		if(e instanceof ErrorCodesException){
			r.setCode(((ErrorCodesException) e).getCode());
			r.setMsg(e.getMessage());
		}
		else {
			r.Error("处理数据异常", null);
		}
		return r;
	}

	/**
	 * validation Exception
	 *
	 * @param exception
	 * @return Ret
	 */
	@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public Ret bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		String msg = "传入数据异常："+fieldErrors.get(0).getDefaultMessage();
		log.warn(fieldErrors.get(0).getDefaultMessage());
		Ret r=  new Ret();
		r.Error(msg, null);
		return r;
	}

}
